//
//  MyMessViewController.m
//  LazyCat
//
//  Created by zhanshu on 15/9/7.
//  Copyright (c) 2015年 zhanshu. All rights reserved.
//

#import "MyMessViewController.h"
#import "MyHeaderTableViewCell.h"
#import "MyTableViewCell.h"
#import "MyMessTableViewCell.h"
@interface MyMessViewController ()<UITableViewDataSource,UITableViewDelegate,UITextFieldDelegate>{
    NSMutableArray *messArr;
    NSArray *imgArr;
    UIImage *headerImg;//头像
    NSArray *titleArr;
    UIView *popView;
    UIImageView *barCodeImg;
}

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@end

@implementation MyMessViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self initNav:@"我的详情" doBack:YES];
    titleArr = @[@[@"",@"手机号码",@"真实姓名",@"证件号码",@"邮箱地址"],@[@"二维码",@"我的关注",@"我的收藏",@"足迹",@"修改密码"]];
     NSArray *arr = @[@"",[[AppData share].mobile safeString],[[AppData share].realname safeString],[[AppData share].cardno safeString],[[AppData share].email safeString]];
    
    messArr = [[NSMutableArray alloc] initWithArray:arr];
    imgArr = @[@"我的详情_r1_c2.png",@"我的详情_r2.png",@"我的详情_r3.png",@"我的详情_r4.png",@"我的详情_r9_c1.png"];
    
//    headerImg = [UIImage imageNamed:[[AppData share].img safeString]];
    
    [_tableView registerNib:[UINib nibWithNibName:@"MyHeaderTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"cell1"];
    [_tableView registerNib:[UINib nibWithNibName:@"MyMessTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"cell2"];
    [_tableView registerNib:[UINib nibWithNibName:@"MyTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"cell3"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHident:) name:UIKeyboardWillHideNotification object:nil];
    
    UIButton *rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame = CGRectMake(ScreenWidth-8-40, 20, 40, 44);
    [rightBtn setHitTestEdgeInsets:UIEdgeInsetsMake(0, -10, 0, -10)];
    [rightBtn setTitle:@"保存" forState:UIControlStateNormal];
    [rightBtn setTitleColor:SetColor(240, 170, 16, 1) forState:UIControlStateNormal];
    rightBtn.titleLabel.font = FontSet(14);
    [rightBtn addTarget:self action:@selector(modifyMess) forControlEvents:UIControlEventTouchUpInside];
    [self.navBar addSubview:rightBtn];
    
    
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 50)];
    UIButton *bottomBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    bottomBtn.frame = CGRectMake(10, 10, ScreenWidth-20, 35);
    [bottomBtn setTitle:@"退出登录" forState:UIControlStateNormal];
    [bottomBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    bottomBtn.backgroundColor = SetColor(240, 170, 16, 1);
    [bottomBtn addTarget:self action:@selector(loginOut) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:bottomBtn];
    _tableView.backgroundColor = BackColor;
    _tableView.tableFooterView = view;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [titleArr[section] count];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            return 70;
        }else {
            return 50;
        }
    }else {
        return 50;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 10;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            static NSString *Cell = @"cell1";
            MyHeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Cell];
            if (headerImg) {
                cell.headerImg.image = headerImg;
            }else{
                [cell.headerImg setImageWithURL:[NSURL URLWithString:[[AppData share].img safeString]] placeholderImage:[UIImage imageNamed:@"我的_r1_c4.png"]];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            return cell;
        }else {
            static NSString *Cell = @"cell2";
            MyMessTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Cell];
            
            if (indexPath.row == 1) {
                cell.inputTextField.enabled = NO;
                cell.inputTextField.textColor = [UIColor grayColor];
            }else {
                cell.inputTextField.enabled = YES;
                cell.inputTextField.textColor = [UIColor blackColor];
            }
            
            cell.inputTextField.delegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.inputTextField.tag = 100+indexPath.row;
            cell.titleLable.text = titleArr[indexPath.section][indexPath.row];
            cell.inputTextField.text = messArr[indexPath.row];
            cell.inputTextField.placeholder = titleArr[indexPath.section][indexPath.row];
            return cell;
        }
    }else {
        static NSString *Cell = @"cell3";
        MyTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:Cell];
//        cell.redPointL.hidden = YES;
//        cell.titleLable.text = titleArr[indexPath.section][indexPath.row];
//        cell.imgView.image = [UIImage imageNamed:imgArr[indexPath.row]];
        return cell;
    }
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            [[PhotoPickerManager shared] showActionSheetInView:self.view fromController:self completion:^(UIImage *image) {
                headerImg = image;
                [self sendImg];
            } cancelBlock:^{
                
            }];
        }else {
            
        }
    }else {
        NSString *url = @"";
        NSString *titleName = @"";
        if (indexPath.row == 0) {
            //我的二维码
            [self showUserCode];
            return;
        }else if (indexPath.row == 1) {
            //我的关注
            url = [NSString stringWithFormat:MyFocusList,[AppData share].username,[AppData share].lng,[AppData share].lat,[Utils md5SignStr]];
            titleName = @"我的关注";
        }else if (indexPath.row == 2) {
            //我的收藏
            url = [NSString stringWithFormat:MyCollection,[AppData share].username,[AppData share].lng,[AppData share].lat,[Utils md5SignStr]];
            titleName = @"我的收藏";
        }else if (indexPath.row == 3) {
            //足迹
            url = [NSString stringWithFormat:MyFootLine,[AppData share].username,[AppData share].lng,[AppData share].lat,[Utils md5SignStr]];
            titleName = @"足迹";
        }else {
            url = [NSString stringWithFormat:ModifyPsw,[AppData share].username,[Utils md5SignStr]];
//            http://mtest.ivpin.com/AppAutoLogin?username=18512150193&action=ModifyPWD&sign=2da414273c418cdcaea7ba6e9c49f141
//            
            titleName = @"修改密码";
        }
        Html5ViewController *html5 = [[Html5ViewController alloc] init];
        html5.requestUrl = url;
        html5.titleStr = titleName;
        [self.navigationController pushViewController:html5 animated:YES];
    }
}
#pragma mark- 上传图片
- (void)sendImg {
    //     手机版本号
    NSUserDefaults *userDefaul = [NSUserDefaults standardUserDefaults];
    NSString *iptype = [userDefaul objectForKey:@"iptype"];
    NSString *banben = [userDefaul objectForKey:@"banben"];
    // &terminal=%@&OSVersion=IOS1.0.1
    NSString *url = [NSString stringWithFormat:SendHeaderImg,[AppData share].username,[Utils md5SignStr],iptype,banben];
    [NTNetUtil postImgWithParam:nil requestUrl:url dataArr:@[headerImg] block:^(NTHttpRequest *networkRequest, NSError *error) {
        NSDictionary *dic = networkRequest.responseData;
        NSLog(@"------%@",dic);
        NSString *suc= dic[@"r"];
        if ([suc isEqualToString:@"T"]) {
            [[MessShowView share] showWithMess:@"上传图片成功"];
            [AppData share].shoplogo = dic[@"imgUrl"];
            [_tableView reloadData];
        }else {
            [[MessShowView share] showWithMess:@"上传图片失败"];
        }
    }];}
#pragma mark - 修改信息
- (void)modifyMess {
    [self.view endEditing:YES];
    //control=MemberCommon&action=SaveBase&username=%@&realname=%@&email=%@&cardno=%@&sign=
    NSString *url = [NSString stringWithFormat:ModifyUserMess,[AppData share].username,messArr[1],messArr[2],messArr[4],messArr[3],[Utils md5SignStr]];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [NTNetUtil sendRequestWithUrl:url requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
        NSDictionary *dic = networkRequest.responseData;
        NSString *suc = dic[@"r"];
        if ([suc isEqualToString:@"T"]) {
            [self.navigationController popViewControllerAnimated:YES];
            [[MessShowView share] showWithMess:@"保存成功"];
            [AppData share].realname = messArr[2];
            [AppData share].cardno = messArr[3];
            [AppData share].email = messArr[4];
        }else {
            [[MessShowView share] showWithMess:dic[@"m"]];
        }
    }];
}
#pragma mark - 弹出二维码
#pragma mark-  二维码
-(void)showUserCode
{
    if(!popView)
    {
        UIWindow *keyWindow=[UIApplication sharedApplication].keyWindow;
        popView=[[UIView alloc]initWithFrame:keyWindow.bounds];
        popView.backgroundColor=SetColor(0, 0, 0, .4);
        popView.alpha=0;
        [keyWindow addSubview:popView];
        
        [UIView animateWithDuration:0.35 animations:^{
            popView.alpha=1;
        }];
        
        UITapGestureRecognizer *tap=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hidentPopView)];
        [popView addGestureRecognizer:tap];
        UIView *showView=[[UIView alloc]initWithFrame:CGRectMake((ScreenWidth-270)/2, (ScreenHeight-270)/2, 270, 270)];
        showView.backgroundColor=[UIColor whiteColor];
        [popView addSubview:showView];
        
        UILabel *namelable=[[UILabel alloc]initWithFrame:CGRectMake(10, 0, showView.width-20, 35)];
        namelable.text=@"我的二维码";
        namelable.textAlignment = NSTextAlignmentCenter;
        [showView addSubview:namelable];
        
        barCodeImg=[[UIImageView alloc]initWithFrame:CGRectMake((showView.width-190)/2, 35+(showView.height-70-190)/2, 190, 190)];
        barCodeImg.backgroundColor = [UIColor orangeColor];
        [showView addSubview:barCodeImg];
        
    }
    
    NSString *url = [NSString stringWithFormat:MyCode,[AppData share].username];
//    [barCodeImg setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@""]];
    [barCodeImg sd_setImageWithURL:[NSURL URLWithString:url] placeholderImage:[UIImage imageNamed:@""]];
}
#pragma mark- 我的二维码

-(void)hidentPopView
{
    [UIView animateWithDuration:0.35 animations:^{
        popView.alpha=0;
    } completion:^(BOOL finished) {
        for (UIView *view in popView.subviews) {
            [view removeFromSuperview];
        }
        [popView removeFromSuperview],popView=nil;
    }];
}
#pragma mark - 退出登录
- (void)loginOut {
    //将当前登陆用户信息清空
    
    [NTNetUtil sendRequestWithUrl:LoginOut requestName:nil method:NTRequestMethodGET parameters:nil block:^(NTHttpRequest *networkRequest, NSError *error) {
        NSDictionary *dic = networkRequest.responseData;
        NSString *suc = dic[@"r"];
        if ([suc isEqualToString:@"T"]) {
            //退出登陆成功
            [[AppData share] clearValue];
//            [NSUserDefualManager storageValue:@"" forKey:UserName];
            NSString *name = [NSUserDefualManager getValueByKey:UserName];
            NSLog(@"%@",name);
            [NSUserDefualManager storageValue:@"" forKey:Psw];
            [AppData share].baseTabVC.redLable.hidden = YES;
            [[AppData share].baseTabVC theShoppingCartCount:0];
            [NSUserDefualManager storageValue:@"0" forKey:@"doLogin"];
            
            [self.navigationController popViewControllerAnimated:NO];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"PopLoginView" object:nil];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"ClearBuyCount" object:nil];
        }else {
            [[MessShowView share] showWithMess:dic[@"m"]];
        }
    }];
    
    
}
#pragma mark - 通知事件
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}
- (void)textFieldDidBeginEditing:(UITextField *)textField {
    
}
- (void)textFieldDidEndEditing:(UITextField *)textField {
    NSInteger tag = textField.tag - 100;
    [messArr replaceObjectAtIndex:tag withObject:textField.text];
}
- (void)keyboardWillShow:(NSNotification *)notifi {
    NSDictionary* info = [notifi userInfo];
    //kbSize即為鍵盤尺寸 (有width, height)
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;//得到鍵盤的高度
    _tableView.contentInset = UIEdgeInsetsMake(0, 0, kbSize.height, 0);
}
- (void)keyboardWillHident:(NSNotification *)notifi {
    _tableView.contentInset = UIEdgeInsetsZero;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
